import 'package:flutter/material.dart';

// 一个简单的 InheritedWidget，用于提供缩放比例
class ScaleFactor extends InheritedWidget {
  final double factor;

  const ScaleFactor({
    super.key,
    required this.factor,
    required super.child,
  });

  static ScaleFactor of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<ScaleFactor>()!;
  }

  @override
  bool updateShouldNotify(ScaleFactor oldWidget) {
    // 当 factor 改变时，通知所有依赖它的子组件更新
    return factor != oldWidget.factor;
  }
}

class ScaleFactorApp extends StatefulWidget {
  const ScaleFactorApp({super.key});

  @override
  State<ScaleFactorApp> createState() => _ScaleFactorAppState();
}

class _ScaleFactorAppState extends State<ScaleFactorApp> {
  double _scale = 1.0;

  @override
  Widget build(BuildContext context) {
    return ScaleFactor(
      // 将状态 _scale 提供给子树
      factor: _scale,
      child: MaterialApp(
        home: Scaffold(
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // 这个 CustomScaledBox 依赖 ScaleFactor
                const CustomScaledBox(),
                Slider(
                  value: _scale,
                  min: 0.5,
                  max: 2.0,
                  onChanged: (value) => setState(() => _scale = value),
                ),
                Text('缩放比例: ${_scale.toStringAsFixed(1)}x'),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

class CustomScaledBox extends LeafRenderObjectWidget {
  const CustomScaledBox({super.key});

  @override
  RenderObject createRenderObject(BuildContext context) {
    // 创建时从 InheritedWidget 获取初始值
    final scale = ScaleFactor.of(context).factor;
    print('创建 RenderObject: Scale=$scale');
    return RenderCustomScaledBox(scale: scale);
  }

  @override
  void updateRenderObject(BuildContext context, RenderCustomScaledBox renderObject) {
    // 这个方法的调用时机：
    // ScaleFactor 中的 factor 发生变化，因为它是一个 InheritedWidget。
    // Flutter 标记所有依赖它的组件（包括这个）需要重建。
    // 这个 Element 的 build 方法被重新调用，虽然 CustomScaledBox 构造函数没有参数，
    // 但因为它依赖的 InheritedWidget 数据变了，Flutter 依然会认为它是一个"新的"Widget，
    // 从而触发 didUpdateWidget 和 updateRenderObject。
    final newScale = ScaleFactor.of(context).factor;
    print('更新 RenderObject: Old Scale=${renderObject.scale} -> New Scale=$newScale');
    renderObject.scale = newScale;
  }
}

class RenderCustomScaledBox extends RenderBox {
  double _scale;

  RenderCustomScaledBox({required double scale}) : _scale = scale;

  double get scale => _scale;
  set scale(double value) {
    if (_scale == value) return;
    _scale = value;
    markNeedsLayout(); // 缩放比例变了，需要重新计算布局
  }

  @override
  void performLayout() {
    // 将一个 100x100 的盒子按比例缩放
    size = Size(100 * _scale, 100 * _scale);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    final Paint paint = Paint()..color = Colors.amber;
    context.canvas.drawRect(offset & size, paint);
  }
}